import { App, Editor,  Modal, Setting } from 'obsidian';


export type SubmitHandler = (result: string) => void

export  class AddCodeBlockModal extends Modal {
	language: string
	code: string
	need_format: boolean
	onSubmit: SubmitHandler
	editor: Editor
	default_lang:string

	constructor(app: App, editor: Editor,defualt_lang:string='') {
		super(app)
		this.editor = editor
		this.default_lang=defualt_lang
		// console.log('Modal constrctor:',this.editor)		
	}

	// _can_open() {
	// 	if (this.editor.somethingSelected() == false &&
	// 		this.editor.getCursor().ch != 0) {
	// 		return false
	// 	}
	// 	return true
	// }

	_create_code_block(): string {
		let block_tag = '```'
		return `${block_tag}${this.language}\n${this.code}\n${block_tag}`
	}

	_add_code_block() {
		let insert_line_id: number
		if (this.editor.somethingSelected()) {
			let cursor = this.editor.getCursor('from')
			insert_line_id = cursor.ch == 0 ? cursor.line : cursor.line + 1
			
			let end_cursor=this.editor.getCursor('to')
			let line=this.editor.getLine(end_cursor.line)
			if (line.length>end_cursor.ch){
				
				this.editor.replaceSelection('\n\n')
			}else{
				this.editor.replaceSelection('\n')

			}
		} else {
			let cursor = this.editor.getCursor()
			let line = this.editor.getLine(cursor.line)
			insert_line_id=cursor.line
			if (line){
				insert_line_id++
				this.editor.replaceRange('\n',{line:cursor.line,ch:line.length})
			}
		}
		this.editor.replaceRange(this._create_code_block(), { line: insert_line_id, ch: 0 })
	}

	// _format_code(code:string):string[]{

	// }

	onOpen(): void {
		// if (this._can_open()==false){
		// 	new Notice('Can not insert code block between a line!')
		// 	return
		// }
		const { contentEl } = this


		new Setting(contentEl)
			.setName("Language")
			.addText(text => {
				text.setPlaceholder(this.default_lang)
				text.onChange(value => {
					this.language = value
				})
			})

		new Setting(contentEl)
			.setName("Code Text")
			.addTextArea(text => {
				text.setPlaceholder(this.editor.getSelection())
				// text.setValue(this.editor.getSelection())
				this.code = this.editor.getSelection()
				text.onChange(value => {
					this.code = value
				})
			})

		// new Setting(contentEl)
		//     .setName('Format Code')
		//     .addToggle(
		//         tg=>{
		//             tg.onChange(value=>this.need_format=value)
		//         }
		//     )

		new Setting(contentEl)
			.addButton(btn => {
				btn.setButtonText('Confirm')
					.setCta()
					.onClick(() => {
						this._add_code_block()
						this.close()
					})
			})
			.addButton(btn => {
				btn.setButtonText('Cancel')
					.setCta()
					.onClick(() => this.close())
			})

	}

	onClose(): void {
		this.contentEl.empty()
		this.editor = null
	}
}

